package cn.edu.bzu.aaa.servlet.loginregistservlet;

import cn.edu.bzu.aaa.model.User;
import cn.edu.bzu.aaa.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;

@WebServlet("/regist")
public class registservlet extends HttpServlet {
    private UserService userService;

    public registservlet() {
        this.userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String userTypeStr = request.getParameter("userType");
        String title = request.getParameter("title");

        // 将userType转换为int
        int userType = Integer.parseInt(userTypeStr);

        // 创建User对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setUserType(userType);
        user.setTitle(title);
        user.setRegistrationDate(new java.sql.Date(new Date().getTime())); // 修改后的代码
        user.setLastLoginDate(null);
        user.setLocked(false);

        // 根据userType设置IsRegistrationComplete
        if (userType == 2 || userType == 3) {
            user.setRegistrationComplete(false);
        } else if (userType == 4) {
            user.setRegistrationComplete(true);
        }

        // 插入用户到数据库
        userService.add(user);

        // 注册成功提示
        if (userType == 2 || userType == 3) {
            request.getRequestDispatcher("/registtt.html").forward(request, response);
        } else if (userType == 4) {
            request.getRequestDispatcher("/login.html").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
